package com.fin.quant.domain.repository.impl;

import com.fin.quant.domain.entity.TagEntity;
import com.fin.quant.domain.mapstruct.TagMapperStruct;
import com.fin.quant.domain.repository.TagRepository;
import com.fin.quant.instra.mysql.mapper.TagMapper;
import com.fin.quant.instra.mysql.model.Tag;
import com.fin.quant.instra.mysql.model.TagExample;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 标签仓储实现
 */
@Service
@Slf4j
public class TagRepositoryImpl implements TagRepository {

    @Autowired
    private TagMapper tagMapper;

    @Override
    public Map<Long, TagEntity> getTagsMap(List<Long> tagIdList) {
        if (CollectionUtils.isEmpty(tagIdList)) {
            return Collections.emptyMap();
        }

        try {
            TagExample example = new TagExample();
            example.createCriteria().andTagIdIn(tagIdList);
            List<Tag> tags = tagMapper.selectByExample(example);

            if (CollectionUtils.isEmpty(tags)) {
                return Collections.emptyMap();
            }

            return tags.stream()
                    .map(TagMapperStruct.INSTANCE::model2Entity)
                    .collect(Collectors.toMap(TagEntity::getTagId, tag -> tag));
        } catch (Exception e) {
            log.error("获取标签映射失败, tagIdList: {}", tagIdList, e);
            return Collections.emptyMap();
        }
    }
}
